package com.nus.parsers;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Calendar;
import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.json.JSONObject;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Intent;

import com.nus.AlarmReceiver;
import com.nus.NUS_Android;
import com.nus.SportsActivity;

public class NdroidAPI {
	public static String formatDate(String jsonString) {

		String JSONDateToMilliseconds = "\\/(Date\\((.*?)(\\+.*)?\\))\\/";
		Pattern pattern = Pattern.compile(JSONDateToMilliseconds);
		Matcher matcher = pattern.matcher(jsonString);
		String result = matcher.replaceAll("$2");
		Date date = new Date(new Long(result));

		return date.toGMTString();

	}

	public static String getName() {
		String response = null;
		String url = "https://ivle.nus.edu.sg/api/Lapi.svc/UserName_Get?APIKey=W7RtgW7GZKUpaEkJ1NwUD&Token="
				+ NUS_Android.IVLE_Token + "&output=json";

		try {
			response = getResponseText(url);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		String newname = response.replace('"', ' ');
		return newname;
	}

	public static String getResponseText(String stringUrl) throws IOException {
		StringBuilder response = new StringBuilder();

		URL url = new URL(stringUrl);
		HttpURLConnection httpconn = (HttpURLConnection) url.openConnection();
		if (httpconn.getResponseCode() == HttpURLConnection.HTTP_OK) {
			BufferedReader input = new BufferedReader(new InputStreamReader(
					httpconn.getInputStream()), 8192);
			String strLine = null;
			while ((strLine = input.readLine()) != null) {
				response.append(strLine);
			}
			input.close();
		}
		return response.toString();
	}
}
